package org.jackysoft.security.cas;

import org.jackysoft.entity.User;
import org.jackysoft.service.UserService;
import org.jasig.cas.authentication.handler.AuthenticationException;
import org.jasig.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.springframework.util.StringUtils;

public class SystemUsernamePasswordAuthenticationHandler extends
		AbstractUsernamePasswordAuthenticationHandler {

	private UserService userService;

	public SystemUsernamePasswordAuthenticationHandler() {}

	@Override
	protected boolean authenticateUsernamePasswordInternal(
			UsernamePasswordCredentials credentials)
			throws AuthenticationException {
		String username = credentials.getUsername();
		String password = credentials.getPassword();

		
		User user = null;
		log.info("User "  +username +" will be check!");
		user = userService.get(username);
		if (user == null)return false;
		if (!user.isEnabled()) return false;
		String pwd = user.getPassword();
		Boolean nameable = StringUtils.hasText(username);
		Boolean passable = StringUtils.hasText(password);
		Boolean passequalsable = password.equals(getPasswordEncoder().encode(pwd));
		if (nameable && passable && passequalsable) {
			log.info("User " + username + " authentication success!");
			return true;
		}
		log.info("User " + username + " authentication failed! ");
		return false;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
